import re

# CodeShare Snippet http://www.codeshare.co/20/2/
def maximum_by(measure, xs):
    return max(xs, key=measure)
# End CodeShare Snippet

# CodeShare Snippet http://www.codeshare.co/43/3/
def wrap_fields(wrapper, dictionary):
    return dict( (k, (wrapper[k](v) if k in wrapper else v))
                 for k, v in dictionary.items() )
# End CodeShare Snippet

# CodeShare Snippet http://www.codeshare.co/24/2/
def initial_whitespace(line):
    return re.search(r'^\s*', line).group(0)
# End CodeShare Snippet

# CodeShare Snippet http://www.codeshare.co/26/10/
def strip_indent(text):
    lines = text.splitlines()
    all_ws = re.compile('^\s*$')
    lengths = [ len(initial_whitespace(l)) for l in lines if not all_ws.match(l) ]
    if not lengths:
        return ("", "")
    initial = min(lengths)
    ret = ('\n'.join(map(lambda l: l[initial:], lines)), " " * initial)
    return ret
# End CodeShare Snippet

# CodeShare Snippet http://www.codeshare.co/28/1/
def indent_by(indent, text):
    return '\n'.join(map(lambda s: indent + s, text.splitlines())) + '\n'
# End CodeShare Snippet

# CodeShare Snippet http://www.codeshare.co/63/2/
def normalize_code(code):
    (s,indent) = strip_indent(code)
    return (s.strip() + "\n", indent)
# End CodeShare Snippet
